// 登录与注册的模块
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api";
import { setToken, removeToken } from "@/utils/token"
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        // console.log(result);
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user);
        // console.log(result);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        // console.log("userLogin:",result);
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            // 设置TOKEN值
            setToken(result.data.token)
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息s
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        // console.log("getUserInfo:", result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userLogout({ commit }) {
        let result = await reqLogout();
        // actions里不能操作state，提交mutations修改state
        if (result.code == 200) {
            commit("CLEAR");
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
};

const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        // console.log("token:", token);
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    // 清除本地数据
    CLEAR(state) {
        state.token = ''
        state.userInfo = {}
        removeToken();
    }
};

const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo: {}
};

const getters = {};

export default {
    state,
    mutations,
    actions,
    getters
}